

package com.gmail.avereshchaga.validation;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author <a href="mailto:avereshchaga@gmail.com">Vereshchaga Alexey</a>
 */
public class AlphanumericVerifier extends InputVerifier {

    @Override
    public boolean verify(JComponent input) {
        String nameStr = ((JTextField) input).getText().trim();
        Pattern pattern = Pattern.compile("[a-zA-Z0-9]{0,}");
        Matcher m = pattern.matcher(nameStr);
        if (m.matches() /*&& !(nameStr.equals(""))*/) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public boolean shouldYieldFocus(JComponent input) {
        boolean inputOK = verify(input);
        if (inputOK) {
            return true;
        } else {
            JOptionPane.showMessageDialog(null, "Field \"Name\" must be alphanumeric", "Warning", 2);
            return false;
        }
    }
}
